//
//  FilterResultViewController.m
//  Finance
//
//  Created by cheng xiang on 13-8-9.
//  Copyright (c) 2013年 cheng xiang. All rights reserved.
//

#import "FilterResultViewController.h"
#import "AnalysisJson.h"
#import "MultiThreading.h"
#import "ProductListCell.h"
#import "NearbyDetailViewController.h"

@interface FilterResultViewController ()

@end

@implementation FilterResultViewController

@synthesize pageIndex = _pageIndex,currentOffsetPoint = _currentOffsetPoint;
@synthesize waitingView = _waitingView, activityView = _activityView,dataArray = _dataArray;
@synthesize loadFooterView = _loadFooterView, reloading = _reloading, conditionDic = _conditionDic;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStyleBordered target:self action:@selector(goReturn)];
    [leftItem setBackgroundImage:[UIImage imageNamed:@"btn.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
    self.navigationItem.leftBarButtonItem = leftItem;
    UIColor* bk = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"beij.png"]];
    [self.tableView setBackgroundColor:bk];
    [self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld context:NULL];
    
    _waitingView = [[UIView alloc] initWithFrame:self.view.bounds];
    _waitingView.alpha = 0.6;
    _waitingView.backgroundColor = [UIColor lightGrayColor];
    
    _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    _activityView.alpha = 1;
    _activityView.center = _waitingView.center;
    [self.view addSubview:_activityView];
    [self.view addSubview:_waitingView];
    
    [self controlActivity:YES];
    
    _dataArray = [[NSMutableArray alloc] init];
    
    if (_loadFooterView == nil) {
		
		_loadFooterView = [[LoadMoreFooterView alloc] initWithFrame: CGRectZero];
		[self.tableView addSubview:_loadFooterView];
	}
    
    [self packageRequest];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if([keyPath isEqualToString:@"contentSize"])
    {
        if ([_dataArray count] >= AMOUNT_MIN.intValue) {
            _loadFooterView.frame = CGRectMake(0.0f, self.tableView.contentSize.height, 320, 250);
        }else{
            _loadFooterView.frame = CGRectZero;
        }
    }
}

- (void)controlActivity:(BOOL)animating
{
    if (animating) {
        //显示正在加载画面
        [self.view bringSubviewToFront:_waitingView];
        [self.view bringSubviewToFront:_activityView];
        _waitingView.hidden = NO;
        _activityView.hidden = NO;
        [_activityView startAnimating];
    }else{
        [_activityView stopAnimating];
        [_activityView setHidden:YES];
        [_waitingView setHidden:YES];
        [self.view sendSubviewToBack:_waitingView];
        [self.view sendSubviewToBack:_activityView];
    }
    
}

-(void)viewDidUnload
{
    _loadFooterView = nil;
    [super viewDidUnload];
}

- (void)dealloc
{
    [self.tableView removeObserver:self forKeyPath:@"contentSize"];
}

- (void)goReturn
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)packageRequest
{
    //组请求报文
    NSDictionary *header = [AnalysisJson PackageJsonHeader:@"W102"];
    self.pageIndex = 0;
    NSDictionary *body = [self PackageBody:self.pageIndex];
    NSData *requestJson = [AnalysisJson PackageJsonFromHeader:header andBody:body];
    
    //发送报文
    [self getTableData: requestJson];
}

//每次组报文需要实现类似组body的方法
- (NSDictionary *)PackageBody:(int)index
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"pageIndex"] = [NSString stringWithFormat:@"%d",index];
    dic[@"pageSize"] = AMOUNT_MIN;
    for (NSString *key in self.conditionDic.allKeys) {
        NSString *value = [self.conditionDic objectForKey:key];
        if ([key isEqualToString:@"产品类型"]) {
            if ([value isEqualToString:@"保本"]) {
                value = @"3";
            }else if([value isEqualToString:@"非保本"]){
                value = @"5";
            }
        }
        if ([key isEqualToString:@"货币类型"]) {
            if ([value isEqualToString:@"人民币"]) {
                value = @"1";
            }else{
                value = @"2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28";
            }
        }
        NSString *condition = @"";
        if ([key isEqualToString:@"预期收益率"]) {
            condition = @"expectedYield";
        }else if ([key isEqualToString:@"货币类型"]){
            condition = @"currency";
        }else if ([key isEqualToString:@"认购起点"]){
            condition = @"startMoney";
        }else if ([key isEqualToString:@"产品类型"]){
            condition = @"prodType";
        }else if ([key isEqualToString:@"起售时间"]){
            condition = @"beginTime";
        }else{
            condition = key;
        }
        if (![value isEqualToString:@"不限"]) {
            [dic setObject:value forKey:condition];
        }
    }
    return dic;
}

- (void)getTableData:(NSData *)data
{
    [MultiThreading getDataFromNetwork:[SERVICE_URL stringByAppendingString:@"QueryProdInfo"] toObject:self callBack:@selector(requestCallBack:) withBody:data];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [_dataArray objectAtIndex:[indexPath row]];
    NearbyDetailViewController *aController = [[NearbyDetailViewController alloc] init];
    aController.proId = [dic objectForKey:@"prodId"];
    [self.navigationController pushViewController:aController animated:YES];
}

- (void)requestCallBack:(NSDictionary *)dic
{
    [self controlActivity:NO];
    NSObject *body = dic[@"body"];
    NSLog(@"%@",[body class]);
    if([body isKindOfClass:[NSDictionary class]] && [(NSDictionary *)body objectForKey:@"products"] != nil)
    {
        [self.dataArray addObjectsFromArray:[(NSDictionary *)body objectForKey:@"products"]];
    }
    
    [self doneLoadingTableViewData];
    [self.tableView reloadData];
}

#pragma mark -
#pragma mark Data Source Loading / Reloading Methods

- (void)reloadTableViewDataSource{
	
	//  should be calling your tableviews data source model to reload
	//  put here just for demo
	_reloading = YES;
	[self packageRequest];
    
}

- (void)doneLoadingTableViewData{
	
	//  model should call this when its done loading
	_reloading = NO;
    [_loadFooterView loadMoreScrollViewDataSourceDidFinishedLoading:self.tableView];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

-(void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    self.currentOffsetPoint = scrollView.contentOffset;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //CGPoint pt = scrollView.contentOffset;
    //if (self.currentOffsetPoint.y < pt.y) {
    if (_loadFooterView.delegate == nil) {
        return;
    }
    [_loadFooterView loadMoreScrollViewDidScroll:scrollView];
	//}
    
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //CGPoint pt = scrollView.contentOffset;
    //if (self.currentOffsetPoint.y < pt.y) {
    if (_loadFooterView.delegate == nil) {
        return;
    }
    [_loadFooterView loadMoreScrollViewDidEndDragging:scrollView];
	//}
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([_dataArray count] >= AMOUNT_MIN.intValue) {
        _loadFooterView.delegate = self;
        _loadFooterView.arrowImage.hidden = NO;
    }else{
        _loadFooterView.delegate = nil;
        _loadFooterView.arrowImage.hidden = YES;
    }
    return [_dataArray count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = [NSString stringWithFormat:@"cell at %d",indexPath.row];
    ProductListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ProductListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        //        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        //        UIImageView *lineImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 78, cell.frame.size.width, 2)];
        //        lineImageView.image = [UIImage imageNamed:@"line-gray.png"];
        //        [cell.contentView addSubview:lineImageView];
        
    }
    NSDictionary *dic = [_dataArray objectAtIndex:[indexPath row]];
    [cell drawCell:dic];
    return cell;
}

#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods

- (void)loadMoreTableFooterDidTriggerRefresh:(LoadMoreFooterView *)view{
	_pageIndex++;
	[self reloadTableViewDataSource];
    
    
	//[self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:4.0];
	
}

- (BOOL)loadMoreTableFooterDataSourceIsLoading:(LoadMoreFooterView *)view{
	
	return _reloading; // should return if data source model is reloading
	
}

@end
